﻿using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Edu.Http;
using Edu.Http.Extensions;
using Edu.Http.Proxy;
using Infrastructure.Config.Core.External;
using Infrastructure.ExternalService.Core.Responses;
using Infrastructure.ExternalService.Core.User;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Infrastructure.ExternalService.Core.Imp.User
{
    public class UserExternal : BaseHttpClient, IUserExternal
    {
        private readonly OrderCenterApiOptions _orderingOptions;
        public IAccessTokenProvider TokenProvider { get; set; }

        public UserExternal(IOptions<OrderCenterApiOptions> options, HttpClient client, ILoggerFactory loggerFactory)
            : base(client, loggerFactory, options.Value.AuthOptions.EndPoint)
        {
            _orderingOptions = options.Value ?? throw new HttpProxyException($"{nameof(UserExternal)}配置获取失败");
            loggerFactory.CreateLogger<UserExternal>();
        }

        /// <summary>
        /// 设置BaseHttpClient的BaseAddress：该值默认是从构造函数传入的，但重写该方法可以改变该值
        /// </summary>
        /// <returns></returns>
        protected override string SetHttpClientBaseAddress()
        {
            return null;
        }

        public async Task<IEnumerable<UserRoleInfo>> GetUserRolesAsync(GetUserRolesRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);

            var response = await GetAsync<WrapResponse<UserRolesData>>(_orderingOptions.AuthOptions.GetUserRoles
                                                                       + "?" + formStr);
            if (response.Code.Equals(ClientReturnCode.Success) && response.Data != null)
            {
                return response.Data.data;
            }

            if (response.Data == null)
            {
                throw new HttpProxyException($"查询用户的角色返回错误:{response.Msg}");
            }

            throw new HttpProxyException($"{response.Msg}");
        }

        public async Task<IEnumerable<UserRoleInfo>> GetAllRolesAsync(GetUserRolesRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);

            var response = await GetAsync<WrapResponse<UserRolesData>>(_orderingOptions.AuthOptions.GetAllRoles
                                                                       + "?" + formStr);
            if (response.Code.Equals(ClientReturnCode.Success) && response.Data != null)
            {
                return response.Data.data;
            }

            if (response.Data == null)
            {
                throw new HttpProxyException($"查询用户的角色返回错误:{response.Msg}");
            }

            throw new HttpProxyException($"{response.Msg}");
        }

        public async Task<UserInfo> GetUserAsync(GetUserRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);

            var response =
                await GetAsync<WrapResponse<UserInfo>>(_orderingOptions.AuthOptions.GetUserInfo + "?" + formStr);
            if (response.Code.Equals(ClientReturnCode.Success) && response.Data != null)
            {
                return response.Data;
            }

            if (response.Data == null)
            {
                throw new HttpProxyException($"查询用户信息返回错误:{response.Msg}");
            }

            throw new HttpProxyException($"{response?.Msg}");
        }

        public async Task<UserProfiles> GetUserIdsAsync(GetUserIdsRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);

            var response =
                await GetAsync<WrapResponse<UserProfiles>>(_orderingOptions.AuthOptions.GetUserIds + "?" + formStr);
            if (response.Code.Equals(ClientReturnCode.Success) && response.Data != null)
            {
                return response.Data;
            }

            if (response.Data == null)
            {
                throw new HttpProxyException($"查询用户ID信息返回错误:{response.Msg}");
            }

            throw new HttpProxyException($"{response.Msg}");
        }

        /// <summary>
        /// 根据优路号集合，获取用户ID集合：接口只返回了用户ID和优路号
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<IEnumerable<UserInfo>> GetUserIdsByYouluNosAsync(GetUserIdsByYouluNoRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);

            var url = _orderingOptions.AuthOptions.GetUserIdsByYouluNos + "?" + formStr;

            var response = await GetAsync<WrapResponse<IEnumerable<UserInfo>>>(url);
            if (response.Code.Equals(ClientReturnCode.Success) && response.Data != null)
            {
                return response.Data;
            }

            if (response.Data == null)
            {
                throw new HttpProxyException($"查询用户信息返回错误:{response.Msg}");
            }

            throw new HttpProxyException($"{response?.Msg}");
        }

        /// <summary>
        /// 根据userid集合，获取用户信息集合
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<IEnumerable<UserInfo>> GetUserInfosByUserIds(GetUserInfosByUserIdsRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);

            var url = _orderingOptions.AuthOptions.GetUserInfosByUserIds + "?" + formStr;

            var response = await GetAsync<WrapResponse<IEnumerable<UserInfo>>>(url);
            if (response.Code.Equals(ClientReturnCode.Success) && response.Data != null)
            {
                return response.Data;
            }

            if (response.Data == null)
            {
                throw new HttpProxyException($"查询用户信息返回错误:{response.Msg}");
            }

            throw new HttpProxyException($"{response?.Msg}");
        }

        /// <summary>
        /// 根据UserId/YouluNumber获取曾用收据号，基础数据响应数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="HttpProxyException"></exception>
        public async Task<IEnumerable<UserOldMobileInfo>> GetOldMobileByUserIds(GetOldMobileByUserIdsRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);

            var url = _orderingOptions.AuthOptions.GetOldMobileByUserIds + "?" + formStr;

            var response = await GetAsync<WrapResponse<IEnumerable<UserOldMobileInfo>>>(url);
            if (response.Code.Equals(ClientReturnCode.Success) && response.Data != null)
            {
                return response.Data;
            }

            if (response.Data == null)
            {
                throw new HttpProxyException($"查询用户信息返回错误:{response.Msg}");
            }

            throw new HttpProxyException($"{response?.Msg}");
        }


        /// <summary>
        /// 根据曾用手机号，获取用户UserId
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="HttpProxyException"></exception>
        public async Task<List<string>> GetUserIdByOldMobile(GetUserIdByOldMobileRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);

            var url = _orderingOptions.AuthOptions.GetUserIdByOldMobile + "?" + formStr;

            var response = await GetAsync<WrapResponse<List<string>>>(url);
            if (response.Code.Equals(ClientReturnCode.Success) && response.Data != null)
            {
                return response.Data;
            }

            if (response.Data == null)
            {
                throw new HttpProxyException($"查询用户信息返回错误:{response.Msg}");
            }

            throw new HttpProxyException($"{response?.Msg}");
        }



        /// <summary>
        /// 根据手机号集合，获取用户信息（若要获取姓名，需设置moreInfo=Y）
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="HttpProxyException"></exception>
        public async Task<IEnumerable<UserInfo>> GetUserInfosByMobilesAsync(GetUserInfosByMobilesRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);

            var url = _orderingOptions.AuthOptions.GetUserInfosByMobiles + "?" + formStr;

            var response = await GetAsync<WrapResponse<WrapResponse<IEnumerable<UserInfo>>>>(url);

            if (response.Code.Equals(ClientReturnCode.Success) && response.Data != null)
            {
                return response.Data.Data;
            }

            if (response.Data == null)
            {
                throw new HttpProxyException($"查询用户信息返回错误:{response.Msg}");
            }

            throw new HttpProxyException($"查询用户信息返回错误:{response}");
        }

        public async Task<List<EmployeeInfo>> GetEmployeeListAsync(GetEmployeeListRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);

            var url = _orderingOptions.AuthOptions.GetEmployeeList + "?" + formStr;

            var response = await GetAsync<WrapResponse<List<EmployeeInfo>>>(url);

            if (response.Data == null)
            {
                throw new HttpProxyException($"查询员工信息返回错误:{response.Msg}");
            }

            if (response.Code.Equals(ClientReturnCode.Success) && response.Data != null)
            {
                return response.Data;
            }

            throw new HttpProxyException($"查询员工信息返回错误:{response}");
        }
    }
}